#!/usr/bin/env python
# -*- coding: utf-8 -*-

import traceback
from dbpoolpy import install, get_connection_exception


DATABASES_POOL = {
    "imlf": {
        "engine": "pymysql",  # db type, eg: mysql, sqlit, pymysql
        "db": "imlf",  # db name
        "host": "10.12.3.179",  # db host
        "port": 51000,  # db port
        "user": "atpdev",  # db user
        "passwd": "atp@GW123",  # db password
        "charset": "utf8",  # db charset
        "conn": 10,  # db connections in pool
    },
    "WindFarmdb": {
        "engine": "pymysql",  # db type, eg: mysql, sqlit, pymysql
        "db": "WindFarmdb",  # db name
        "host": "10.12.9.119",  # db host
        "port": 51000,  # db port
        "user": "sf-write",  # db user
        "passwd": "sf-write@goldwind",  # db password
        "charset": "utf8",  # db charset
        "conn": 10,  # db connections in pool
    },
}


def insert_batch(db, table, datas, num=2000):
    """
    批量插入
    """
    try:
        cnt = 0
        while len(datas) > cnt:
            ceil_list = datas[cnt: cnt + num]
            db.insert_list(table, ceil_list)
            cnt += num
    except Exception:
        print(traceback.format_exc())
        raise ValueError("插入数据失败")


def main():
    # 从WindFarmdb wind_farm_info取所有用户列表数据
    users = []
    with get_connection_exception("WindFarmdb") as db:
        users = db.select(
            "wind_farm_info", fields="administrator", other="group by administrator"
        )
    for user in users:
        if user["administrator"]:
            windfarm_wfid = []
            imlf_wfid = []
            # 从WindFarmdb wind_farm_info取wfid数据
            with get_connection_exception("WindFarmdb") as db:
                windfarm_wfid = db.select(
                    "wind_farm_info",
                    fields="wfid",
                    where={"administrator": user["administrator"]},
                )
            # 从imlf实体entity表中取出已有wfid
            with get_connection_exception("imlf") as db:
                imlf_wfid = db.select(
                    "entity", fields="biz_id", where={"username": user["administrator"]}
                )
            windfart_wfid_set = set([i["wfid"] for i in windfarm_wfid])
            imlf_wfid_set = set([i["biz_id"] for i in imlf_wfid])
            # 计算差值
            diff_wfid_set = windfart_wfid_set - imlf_wfid_set
            # 插入增加的wfid
            entity_datas = []
            for i in diff_wfid_set:
                data = {
                    "username": user["administrator"],
                    "biz_id": i,
                    "biz_type": "wfid",
                    "status": 1,
                }
                entity_datas.append(data)
            with get_connection_exception("imlf") as db:
                insert_batch(db, "entity", entity_datas)


if __name__ == "__main__":
    install(DATABASES_POOL)
    main()
